//
// @Auther: by wujehy 
// @Email:wujehy@qq.com
// @Data:20-5-18
// @Time:上午10:48
//

#include <boost/bind.hpp>
#include "SerialClient.h"

#define SERIAL_BUFFER_LEN 1024

SerialClient::SerialClient(std::string portName, int baudrate, int flow_control, int parity_type, int stop_type) : port(
        boost::asio::serial_port(m_ios)), m_buf(SERIAL_BUFFER_LEN, 0)
{
    port.open(portName, ec);
    port.set_option(boost::asio::serial_port::baud_rate(baudrate));    //波特率
    boost::asio::serial_port::flow_control::type flow_control_type;


    port.set_option(boost::asio::serial_port::flow_control(
            (boost::asio::serial_port::flow_control::type) flow_control_type));  //流控制
    port.set_option(boost::asio::serial_port::parity((boost::asio::serial_port::parity::type) parity_type)); //奇偶校验
    port.set_option(boost::asio::serial_port::stop_bits((boost::asio::serial_port::stop_bits::type) stop_type)); //停止位
    port.set_option(boost::asio::serial_port::character_size(8));// 通信字节位数，4—8
    if (ec)
    {
        std::cout << "打开指定的串口失败，错误原因：" << ec.message() << std::endl;
        return;
    }


}

void SerialClient::run()
{
    m_ios.run();
}

void SerialClient::read_buffer(ReadFunction function)
{
//    if (ec)
//    {
//        std::cout << "异步从串口读入数据失败，错误原因：" << ec.message() << std::endl;
//        return;
//    }
//
//    std::string data((char*)&m_buf , byte_read);
//    //收到下位数据
//    std::cout << "收到数据：" << data<< std::endl;

    // 是否转发
//    // 进行处理
//    if (tranToServer)
//    {
//        std::string out(data , byte_read);
//        std::cout << "tet : "<< out<<std::endl;
//        // 发送到服务端的处理
//        this_cli->writemsg(out);
//    }

    port.async_read_some(boost::asio::buffer(m_buf), boost::bind(function, this, boost::ref(port),
                                                                 boost::asio::placeholders::error,
                                                                 boost::asio::placeholders::bytes_transferred));

}

void SerialClient::handle_write(boost::asio::serial_port &port, const boost::system::error_code &ec)
{
    if (ec)
    {
        std::cout << "异步向串口写入数据失败，错误原因：" << ec.message() << std::endl;
        return;
    }
}

void SerialClient::write(std::string &msg)
{
    boost::asio::async_write(port, boost::asio::buffer(msg.c_str(), msg.length()),
                             boost::bind(SerialClient::handle_write, boost::ref(port),
                                         boost::asio::placeholders::error));
}

const SerialClient::buffer_type &SerialClient::getMBuf() const
{
    return m_buf;
}

void SerialClient::stop()
{
    m_ios.stop();
}
